/**
 * Created by mac on 12-1-4.
 * 评论的事件处理
 * 依赖同级目录下的servers.js
 */
(function( $ ) {


    $.fn.comments = function( settings ) {

        var $this = $(this),
            userInfo = userServers.getUserInfo(),
            userAvatar = userInfo.data.userAvatar, //当前用户的头像
            userName = userInfo.data.userName, //获取当前用户名
            userId = userInfo.data.userId,
            userUrl = userInfo.userUrl; //获取当前用户url


        //初始化，默认加载2条微博
        $.infoPageStep = 1; //初始默认页面步长 1
        insertInfoContent({'insertFunction':'html', 'pageStep':$.infoPageStep});


        //事件委托 点赞
        $this.on('click', '.zan', function() {
            var userInfo = userServers.getUserInfo();

            if ( userInfo.userName ) {
                var thisZan = $(this),
                    userName = userInfo.userName,
                    userUrl = userInfo.userUrl;

                //如果是第一次点赞
                if ( !thisZan.data('userName') ) {
                    thisZan.data('userName', userName);
                    //向后端发送数据
                    commentServers.good({'userName': userName}, function() {
                        //前端显示点赞
                        var oCon = thisZan.siblings('.con'),
                            oNum = oCon.find('bdo');

                        oCon.prepend('<span><a href="'+ userUrl +'">'+ userName +'</a></span><em>/</em>');
                        oNum.text( Number(oNum.text())+1 );
                    });
                } else {
                    window.globalLayer.openWarning({'autoClose':true, 'time':1000, 'text':'您已经点过赞了'})
                }
            } else {
                window.globalLayer.openLogin(); //打开登陆提示弹窗
            }
        });


        //事件委托 点击展开评论
        $this.on('click', '.title', function() {
            var thisTit = $(this);

            if ( !thisTit.hasClass('no-h') ) { //当前可点击展开
                thisTit.addClass('no-h').find('i').remove();
                insertCommentContent(thisTit, 1); //插入评论数据
            }
        });


        //事件委托 评论微博 输入框
        $this.on('keydown', '.js-cumment-input', function() {
            var thisInput = $(this),
                oSubmit = thisInput.parents('.input').siblings('.button').find('.js-cumment-button');

            inputRule(thisInput, oSubmit);
        });
        $this.on('keyup', '.js-cumment-input', function() {
            var thisInput = $(this),
                oSubmit = thisInput.parents('.input').siblings('.button').find('.js-cumment-button');

            inputRule(thisInput, oSubmit);
        });


        //事件委托 点击评论微博
        $this.on('click', '.js-cumment-button', function() {
            var userInfo = userServers.getUserInfo();

            if ( userInfo.userName ) {
                var thisButton = $(this),
                    userAvatar = userInfo.userAvatar,
                    userName = userInfo.userName;

                if ( !thisButton.hasClass('button-disabled') ) { //如果该按钮可点击
                    var oListUl = thisButton.parents('.content').eq(0).find('.list ul'),
                        oInput = thisButton.parents('.input-block').find('.js-cumment-input'),
                        commId=thisButton.parents('.goods-description-comment').find("#prodCommId").val();

                    //添加一条评论
                    var data = { //添加
                        'userId':userId,
                        'commId':commId,
                        'commentAvatar': userAvatar,
                        'commentUserName': userName,
                        'commentPublishTime': '刚刚',
                        'commentContent': oInput.val()
                    };

                    //向后端插入该条评论
                    commentServers.addComment(data, function() {
                        //成功之后前端显示评论内容
                        addComment(oListUl, data);
                    });

                    oInput.val('');
                    thisButton.addClass('button-disabled');
                }
            } else {
                window.globalLayer.openLogin(); //打开登陆提示弹窗
            }
        });

        //事件委托 点击回复评论
        $this.on('click', '.reply', function() {
            var userInfo = userServers.getUserInfo();

            if ( userInfo.userName ) {
                var thisReplay = $(this),
                    oParent = thisReplay.parents('.con').eq(0);

                //如果是第一次点击
                if ( !thisReplay.data('hasAppend') ) {
                    addReply( oParent );
                    thisReplay.data('hasAppend', true);
                }
            } else {
                window.globalLayer.openLogin(); //打开登陆提示弹窗
            }
        });


        //事件委托 回复评论输入框
        $this.on('keydown', '.js-input-reply', function() {
            var thisInput = $(this),
                oSubmit = thisInput.parents('.input').siblings('.button').find('.js-button-submitreply');

            inputRule(thisInput, oSubmit);
        });
        $this.on('keyup', '.js-input-reply', function() {
            var thisInput = $(this),
                oSubmit = thisInput.parents('.input').siblings('.button').find('.js-button-submitreply');

            inputRule(thisInput, oSubmit);
        });


        //事件委托 点击回复提交按钮 完成回复内容
        $this.on('click', '.js-button-submitreply', function() {
            var userInfo = userServers.getUserInfo();

            if ( userInfo.userName ) {
                var thisButton = $(this),
                    userAvatar = userInfo.userAvatar,
                    userName = userInfo.userName;

                if ( !thisButton.hasClass('button-disabled') ) {
                    var oListUl = thisButton.parents('.list ul'),
                        oInput = thisButton.parents('.input-block').find('.js-input-reply'),
                        replyUserName = thisButton.parents('.con').find('.user-name').eq(0).find('a').text();

                    //添加一条微博评论
                    //向后端插入该条评论
                    commentServers.addComment({
                        'userId':userId,
                        'commentAvatar': userAvatar,
                        'commentUserName': userName,
                        'commentReplyUserName': replyUserName,
                        'isReply': true,
                        'commentPublishTime': 1,
                        'commentContent': oInput.val()
                    }, function(msg) {
                        addComment(oListUl, msg.data); //前段显示评论内容
                        oInput.val('');
                        thisButton.addClass('button-disabled');
                    });
                }
            } else {
                window.globalLayer.openLogin(); //打开登陆提示弹窗
            }
        });


        //事件委托 点击删除评论或微博
        $this.on('click', '.js-remove-comment', function() {
            var userInfo = userServers.getUserInfo();

            if ( userInfo.userName ) {
                var thisDel = $(this),
                    oParentLi = thisDel.parents('li').eq(0);

                //通知后端删除id为xxx的评论
                commentServers.removeComment({
                    'cid': oParentLi.attr('hid')
                }, function() {
                    removeComment(oParentLi);
                });
            } else {
                window.globalLayer.openLogin(); //打开登陆提示弹窗
            }
        });


        $this.on('click', '.js-remove-comment-comment', function() {
            if ( userName ) {
                var thisDel = $(this),
                    oParentLi = thisDel.parents('li').eq(0);

                //通知后端删除id为xxx的评论
                commentServers.removeCommentComm({
                    'cid': oParentLi.attr('cid')
                }, function() {

                    removeComment(oParentLi);
                });
            } else {
                window.globalLayer.openLogin(); //打开登陆提示弹窗
            }
        });




        //事件委托 点击评论的分页页码切换评论数据
        $this.on('click', '.page a', function() {
            var thisTab = $(this),
                oPage = thisTab.parent(),
                currentPageStep = 0;

            if ( !oPage.data('pageStep') ) { oPage.data('pageStep', 1) } //默认pageStep是1，代表第一页
            currentPageStep = oPage.data('pageStep');

            if ( thisTab.hasClass('pre') ) {

                //用户点击了上一页
                if ( currentPageStep > 1 ) {
                    oPage.data('pageStep', currentPageStep-1);
                }

            } else if ( thisTab.hasClass('next') ) {

                //用户点击了下一页
                oPage.data('pageStep', currentPageStep+1);

            } else {

                //用户点击了分页的页码数，如点击了 1、 2、 3 。。。
                oPage.data( 'pageStep', Number(thisTab.text()) );

            }

            insertCommentContent(thisTab, oPage.data('pageStep')); //插入评论数据
        });

        //********定义一些辅助方法***********

        //输入框内容的规则限制
        function inputRule( $input, $button ) {
            //限制字数
            $.maxTextLen({
                'field': $input,
                'isSubStr': true,
                'callBack': function(data) {
                    //是否激活提交按钮
                    canActiveButton($button, data);
                }
            });
        }

        //判断是否能激活按钮
        function canActiveButton( $obj, boolean ) {
            if ( boolean ) {
                $obj.removeClass('button-disabled');
            } else {
                $obj.addClass('button-disabled');
            }
        }


        //添加回复评论的 输入框 和 回复按钮 html
        function addReply( $obj ) {
            $obj.append(
                '<div class="input-block">\
                    <div class="input">\
                        <input class="js-input-reply" name="" type="text">\
                    </div>\
                    <div class="button">\
                        <button type="button" class="js-button-submitreply button-default button-disabled">回复</button>\
                    </div>\
                </div>'
            );
        }


        //添加一条评论html
        function addComment( $obj, data ) {
            $obj.prepend( getCommentContentHtml(data) );
        }


        //删除一条评论
        function removeComment( $obj ) {
            $obj.remove();
        }


        //加载微博数据并插入到页面中
        function insertInfoContent( configs, callBack ) {
            commentServers.getInfoDatas({
                'currentPage': settings.currentPage, //用户当前请求的页面标记
                'pageStep': configs.pageStep,
                'count': 2 //需要请求的微博条数
            }, function(msg) { //请求之后执行的回调函数
                //插入微博内容
                $this[configs.insertFunction]( getInfoHtml(msg.data) );
                callBack && callBack();
            });
        }


        //插入评论数据
        function insertCommentContent( $thisTab, pageStep ) {
            //获取评论数据
            commentServers.getCommentDatas({
                'currentPage': settings.currentPage, //用户当前请求的页面标记
                'hid': $thisTab.parents('.js-info').attr('hid'), //该条微博的id值
                'pageStep': pageStep, //当前分页的区间，从1开始，代表第一页
                'count': 2 //每次请求时获取的微博条数 即每页条数
            }, function( msg ) {
                var oCommentBox = $thisTab.parents('.js-comment-box');

                //如果是第一次加载数据
                if ( !oCommentBox.data('banInsertBox') ) {
                    oCommentBox.append( getCommentBoxHtml() ); //插入评论的总体html框架
                    oCommentBox.data('banInsertBox', true);
                }

                var oCommentList = oCommentBox.find('.js-comment-list'),
                    oUl = oCommentList.find('ul'),
                    oPage = oCommentList.find('.page'),
                    aCommentData = msg.data.commentData,
                    sCommentContentHtml = '';

                //往刚插入总体框架的ul节点插入获得的评论数据
                for ( var i = 0, iLen = aCommentData.length; i < iLen; i ++ ) {
                    sCommentContentHtml += getCommentContentHtml( aCommentData[i] );
                }
                oUl.html(sCommentContentHtml);

                //插入分页页码
                oPage.html(msg.data.commentPageCode);
            });
        }


        //获取一条评论的html
        function getCommentContentHtml( data ) {
            return '<li cid="'+ data.cid +'">\
                        <div class="user-avatar"><a href="'+ data.commentAvatar +'"><img src="'+ data.commentAvatar +'" width="30" height="30"></a></div>\
                        <div class="con">\
                            <p>'+ (function() {
                                    var tmpStr = '';

                                    if ( data.commentReplyUserName ) {
                                        tmpStr = '<span class="user-name"><a href="'+ data.commentUserUrl +'">'+ data.commentUserName +'</a>：</span>回复<span class="user-name"> <a href="'+ data.commentReplyUserUrl +'">'+ data.commentReplyUserName +'</a></span>';
                                    } else {
                                        tmpStr = '<span class="user-name"><a href="'+ data.commentUserUrl +'">'+ data.commentUserName +'</a></span>';
                                    }
                                    return tmpStr;
                                })() +'：'+ data.commentContent +'</p>\
                            <div class="w-opt"> <span class="time">'+ data.commentPublishTime +'</span> '+ (function() {
      //此处判断该条评论是否为当前用户所有，如果是，则输出删除功能，否则不输出
      return data.userId == userId ? '<span class="js-remove-comment-comment f-red"><a href="javascript:;">删除</a></span>' : '';
  })() +' '+ (function() {
                  //此处判断该条评论是否为当前用户所有，如果是，则不输出回复功能，否则输出
                  return data.userId != userId ? '<span class="reply"><a href="javascript:;">回复</a></span>' : '';
             })() +' </div>\
                        </div>\
                    </li>';
        }


        //微博内容的html
        function getInfoHtml( data ) {
            var str = '';
            for ( var i = 0, iLen = data.length; i < iLen; i ++ ) {
                var infoData = data[i];

                str += '<li class="js-info clearfix" hid="'+ infoData.hid +'">\
                            <div class="user-avatar">\
                                <a href="'+ infoData.hostUserUrl +'">\
                                    <img src="'+ infoData.hostAvatar +'" width="83" height="83">\
                                    <p>'+ infoData.hostUserName +'</p>\
                                </a>\
                            </div>\
                            <div class="goods-description-comment"><i class="i-04"></i>\
                             <input id="prodCommId" class="price" type="hidden" value="'+ infoData.hid +'" />\
                                <div class="description">\
                                    <div class="clearfix">\
                                        <div class="img"><img src="'+ infoData.infoImages +'" width="250" height="250"></div>\
                                        <div class="text-1">\
                                            <div class="con">\
                                                <h2>'+ infoData.infoTitle +'</h2>\
                                                <div class="price"><strong>'+ infoData.infoPrice +'</strong></div>\
                                                <div class="share-more"><span><a href="'+ infoData.infoShareUrl +'">相关分享<strong>'+ infoData.infoShareNum +'条</strong><span></span>进入该商品讨论页<em>&gt;</em></a></span> </div>\
                                            </div>\
                                        </div>\
                                    </div>\
                                    <div class="text-2">\
                                        <p>'+ infoData.infoDescrition +'</p>\
                                    </div>\
                                    <div class="w-opt"> <span class="time">'+ infoData.infoPublishTime +'</span> '+ (function() {
                            //此处判断该条微博是否属于当前用户所有，如果是，则输出删除功能，否则不输出
                            return infoData.userId == userId ? '<span class="js-remove-comment"><a href="javascript:;">删除</a></span>' : '';
                        })() +'</div>\
                                    <div class="follow">\
                                        <div class="con">\
                                        '+ (function() {
                                            //列出点赞的用户
                                            var userStr = '',
                                                aZanData = infoData.infoZanUsers; //<span><a href="#">王二</a></span><em>/</em>

                                            for ( var i = 0, iLen = aZanData.length; i < iLen; i ++ ) {
                                                var currentData = aZanData[i];

                                                if ( i < iLen-1 ) {
                                                    userStr += '<span><a href="'+ currentData.url +'">'+ currentData.userName +'</a></span><em>/</em>';
                                                } else {
                                                    userStr += '<span><a href="'+ currentData.url +'">'+ currentData.userName +'</a></span>';
                                                }
                                            }
                                            return userStr;
                                        })() +'，等<bdo>'+ infoData.infoZanUsers.length +'</bdo>人赞了此分享。 </div>\
                                        <div class="zan"><i class="i-01"></i></div>\
                                    </div>\
                                </div>\
                                <div class="js-comment-box comment">\
                                    <div class="title"><span><em>'+ infoData.infoCommentsNum +'条评论</em><i class="i-03"></i></span></div>\
                                </div>\
                                <div class="bottom"></div>\
                            </div>\
                        </li>'
            }
            return str;
        }


        //获取评论内容的盒子html
        function getCommentBoxHtml() {
            return '<div class="js-comment-content content">\
                        <div class="input-block">\
                            <div class="input">\
                                <input class="js-cumment-input" name="" type="text">\
                            </div>\
                            <div class="button">\
                                <button type="button" class="js-cumment-button button-default button-disabled">评论</button>\
                            </div>\
                        </div>\
                        <div class="js-comment-list list">\
                            <ul></ul><!--此处ul里面放li，每条li代表一条评论-->\
                            <div class="page"></div><!--此处放分页页码-->\
                        </div>\
                    </div>';
        }


        //设置需要对外提供的方法
        $.getInfoHtml = getInfoHtml; //根据返回的微博json数据处理成html
        $.insertInfoContent = insertInfoContent; //加载微博数据并插入到页面中

    };

})( jQuery );